/**
 * After ajax upload file, this script is run again, but jQuery is undefined.
 */
if ((typeof Tacho) == 'undefined' && (typeof jQuery) != 'undefined' ) {

	/**
	 * Tacho object hold all javascript objects and methods used in Tacho,
	 * to separate our script from outer-world.
	 */
	var Tacho = {};
	
	Tacho.DirtyChecker = {
		formsMap : {},
		formsSelector : 'form.tacho_dirty_check',
		dirtyClass : 'tacho_dirty',
		linkToGo: '',
		wait : true,
		observeFormDirty : function(formId) {
			var frm = jQuery('form[id=' + formId + ']');
			if (frm && frm[0] && frm.hasClass('tacho_dirty_check')) {
				this.formsMap[frm[0].id] = frm[0];
				this.observeFieldsOnForm(frm[0].id);
			}
		},
		resetFormDirty : function(formId) {
			var frm = this.formsMap[formId];
			if (frm) {
				this.setFormDirty(frm.id, false);
			}
		},
		// private
		observeFieldsOnForm : function(formId) {
			var frm, frmFieldsSelector, scope;
			
			frm = this.formsMap[formId];
			frmFieldsSelector = 'form[id=' + frm.id + ']';
			
			if (frm) {
				scope = this;
				jQuery(frmFieldsSelector).livequery('submit', function(ev) {
					scope.setFormDirty(frm.id, false);
				});
				jQuery(frmFieldsSelector + ' :input:not(type=checkbox)').livequery('change', function(ev) {
					scope.setFormDirty(frm.id, true);
				});
				jQuery(frmFieldsSelector + ' :input[type=checkbox]').livequery('click', function(ev) {
					scope.setFormDirty(frm.id, true);
				});
			}
		},
		setFormDirty : function(frmId, dirty) {
			if (!frmId) {
				return;
			}
			if (dirty) {
				jQuery('form[id=' + frmId + ']').addClass(this.dirtyClass);
			} else {
				jQuery('form[id=' + frmId + ']').removeClass(this.dirtyClass);
			}
		},
		isFormDirty : function(frmId) {
			return jQuery('form[id=' + frmId + ']').hasClass(this.dirtyClass);
		},
		triggerCalendarInputChange : function(rCldrWrapperId) {
			jQuery('#' + rCldrWrapperId + ' input.rich-calendar-input').trigger('change');
		},
		linkEle : null,
		linkOnClick : function(needCheckDirty, wait) {
			var target;
			
			if (!this.linkEle) {
				return false;
			}
			
			target = this.linkEle.attr('target');
			
			this.linkToGo = this.linkEle.attr('href');
			this.wait = wait;
			
			if (target == '_self') {
				if(needCheckDirty && this.linkToGo) {
					if (!this.checkDirty()) {
						document.getElementById('askForDirtyLeaving').component.show();
						return false;
					}
				}
				Tacho.Mask.showGlass();
				jQuery(window).attr('location', this.linkToGo);
				return false;
			}
			return true;
		},
		checkDirty : function() {
			var k, forms;
			forms = jQuery(this.formsSelector);
			for (i=0; i<forms.length; i++) {
				if (this.isFormDirty(forms[i].id)) {
					// dirty
					return false;
				}
			}
			// clean
			return true;
		},
		saidYesToLeavePage : function() {
			if (this.linkToGo) {
				if (this.wait) {
					Tacho.Mask.show();
				} else {
					Tacho.Mask.showGlass();
				}
				jQuery(window).attr('location', this.linkToGo);
			}
		}
	};
	
	/**
	 * Show a mask to block input and display "please wait..." message.
	 */
	Tacho.Mask = {
	    init : function() {
			var scope;
			
	        // to keep the scope 'this' alive
	        scope = this;
			jQuery(document).keypress(function(e) {
		    	// check if user hit ESC key.
		    	if (e.keyCode == 27) {
			    	scope.hide();
			    	scope.hideGlass();
		    	}
		    });
	    },
	    show : function() {
	    	jQuery.blockUI({
	    		message: jQuery('#maskMsg'),
	    		css: {
	                padding: '5px',
	                backgroundColor: '#000000',
	                opacity: .5,
	                color: '#ffffff'
	            }
	    	}); 
	    },
	    hide : function() {
	    	jQuery.unblockUI();
	    },
	    showGlass : function() {
	    	jQuery.blockUI({
	    		message: null,
	    		overlayCSS: {
		    		backgroundColor: '#000000',
		    		filter: 'alpha(opacity=0)',
		    		opacity: 0.0
				}
	    	});
	    },
	    hideGlass : function() {
	    	jQuery.unblockUI();
	    }
	};
	
	Tacho.Document = {
		fileNameMaxLength : 24,
		onEnterpriseChecked : function(accessEnterpriseEle, accessSecoEle, accessKaiEle) {
			if (jQuery(accessEnterpriseEle).attr('checked')) {
				jQuery(accessSecoEle).attr('checked', true);
				jQuery(accessKaiEle).attr('checked', true);
				jQuery(accessSecoEle).attr('disabled', true);
				jQuery(accessKaiEle).attr('disabled', true);
			} else {
				jQuery(accessSecoEle).attr('disabled', false);
				jQuery(accessKaiEle).attr('disabled', false);
			}
		},
		/** HACK: correct the uploaded file name: get the name only, not the full path in IE. */
		correctFileName : function(className) {
			var fileName, pathSepIdx, newName;
			fileName = jQuery(className + ':first').html();
			if (fileName) {
				pathSepIdx = fileName.lastIndexOf('\\');
		        if (pathSepIdx < 0) {
		            pathSepIdx = fileName.lastIndexOf('/');
		        }
		        newName = fileName.substring(pathSepIdx + 1);
		        newName = Tacho.Utils.cut(newName, this.fileNameMaxLength);
		        jQuery(className + ':first').html(newName);
			}
		},
		/**
		 * Hack richfaces for invisible button Clear all and stop all
		 * because dont need to show that buttons when only one document is uploaded.
		 */
		hideUnusedButtons : function(parentId) {
			var i, button, buttons;
		 	buttons = jQuery('div[id=' + parentId + '] .rich-fileupload-toolbar-decor .rich-fileupload-button-border');
			// i starts from 1, ignore that first button which is 'Add"
		 	for (i = 1 ; i < buttons.length ; i++) {
			 	button = buttons[i];
			 	jQuery(button).addClass('doc-btn-hide');
		 	}
		}
		
	};
	
	Tacho.FullTextSearch = {
		/**
		 * Full text search url must have class "go-to-search".
		 * Fast text search string must have class "search_short_field".
		 */
		doFastSearch : function() {
			jQuery(window).attr('location', this.getHref() + '?searchString=' + this.getSearchString());
		},
		getHref : function() {
			return jQuery('.go-to-search').attr('href');
		},
		getSearchString : function() {
			return encodeURIComponent(jQuery('.search_short_field').attr('value'));
		}
	};
	
	Tacho.Enterprise = {
			mandatoryTextField: function(burNrId, submitButtonId) {
				 
				 Tacho.Enterprise.enableOnlyIfFieldNotEmpty(burNrId, submitButtonId);
				 jQuery('input[id=' + burNrId + ']').
			     keyup(function(event) {
				 		Tacho.Enterprise.enableOnlyIfFieldNotEmpty(burNrId, submitButtonId);
				 });
			},
	
			enableOnlyIfFieldNotEmpty: function(fieldId, submitButtonId) {
	            if (jQuery('input[id=' + fieldId + ']').val() == ""){
				 jQuery('input[id=' + submitButtonId +']').attr('disabled','disabled');
	            } else {
	            	jQuery('input[id=' + submitButtonId +']').removeAttr('disabled');
	            }
			},
	
			setBurnumberCriteria : function(parentId, burNrId, submitButtonId) {
				Tacho.Enterprise.enableOnlyIfFieldNotEmpty(burNrId, submitButtonId);
				
				jQuery("div[id=" + parentId + "] .en-search-burnumber input").attr('disabled', false);
				jQuery("div[id=" + parentId + "] .en-search-burnumber input:first").focus();
				
				jQuery("div[id=" + parentId + "] .en-search-enterprise-info input").attr('disabled', true);
				
				jQuery("div[id=" + parentId + "] .en-search-enterprise-info select").attr('disabled', true);
				
				jQuery("div[id=" + parentId + "] .en-search-radio-by-burNumber input[type=radio]").attr('checked', true);
				jQuery("div[id=" + parentId + "] .en-search-radio-by-enterprise-info input[type=radio]").attr('checked', false);
			},
			
			setEnterpriseInfoCriteria : function(parentId, submitButtonId) {
				jQuery('input[id=' + submitButtonId +']').removeAttr('disabled');
				jQuery("div[id=" + parentId + "] .en-search-burnumber input").attr('disabled', true);
				jQuery("div[id=" + parentId + "] .en-search-enterprise-info input").attr('disabled', false);
				jQuery("div[id=" + parentId + "] .en-search-enterprise-info input:first").focus();
				jQuery("div[id=" + parentId + "] .en-search-enterprise-info select").attr('disabled', false);
				
				jQuery("div[id=" + parentId + "] .en-search-radio-by-burNumber input[type=radio]").attr('checked', false);
				jQuery("div[id=" + parentId + "] .en-search-radio-by-enterprise-info input[type=radio]").attr('checked', true);
			},
			
			refreshSearchCriteriaStatus : function(parentId, submitButtonId) {
				if (jQuery("div[id=" + parentId + "] .en-search-radio-by-burNumber input[type=radio]").attr('checked')) {
                    this.setBurnumberCriteria(parentId, submitButtonId);
                }
                if (jQuery("div[id=" + parentId + "] .en-search-radio-by-enterprise-info input[type=radio]").attr('checked')) {
                	this.setEnterpriseInfoCriteria(parentId, submitButtonId);
                }
			},
			
			setStatusForPostBoxZipAndCity : function(cbPostboxId ,enPostBoxZipId , enPostBoxCityId) {
				var tbEnPostBoxZip =  "input[id=" + enPostBoxZipId + "]";
				var tbEnPostBoxCity = "input[id=" + enPostBoxCityId + "]";
				var cbPostbox = jQuery("input[id=" + cbPostboxId + "]"); 
				
				if (cbPostbox.attr("checked")) {
					jQuery(tbEnPostBoxZip).attr("disabled" , false);
					jQuery(tbEnPostBoxCity).attr("disabled" , false);
				} else if(!cbPostbox.attr("checked")){
					jQuery(tbEnPostBoxZip).attr("disabled" , true);
					jQuery(tbEnPostBoxCity).attr("disabled" , true);
					jQuery(tbEnPostBoxZip).attr("value" , "");
					jQuery(tbEnPostBoxCity).attr("value" , "");
				}
			}
	};
	
	Tacho.Wizard = {
		stepToJump : null,
		checkDirtyForm : function(confirmFormId, wizardFormId) {
			if (Tacho.DirtyChecker.isFormDirty(wizardFormId)) {
				document.getElementById(confirmFormId).component.show();
				return false;
			}
			return true;
		},
		checkDirtyFormOnJump : function(confirmFormId) {
			var formId = jQuery('form.wizard-form').attr('id');
			return this.checkDirtyForm(confirmFormId, formId);
		}
	};
	
	Tacho.Process = {
		updateDateByOtherDate : function(respiteDateComp, notifyDateComp) {
			var respiteDate = respiteDateComp.getSelectedDate();
			if (respiteDate != null) {
				notifyDateComp.selectDate(respiteDate);
			}
		}	
	};
	
	Tacho.Form = {
	
		defaultFocusClass : 'tacho-default-focus',
		defaultButtonClass : 'tacho-default-button',
		onFormRender : function(formClientId){			
			jQuery('form[id=' + formClientId + '] ' + '.' + this.defaultFocusClass + ":not([readonly='readonly']):first").focus();
		}	
	};
	
	Tacho.ModalPanel = {
		initFullScreenModalPanel : function(richModalPanel) {
			var scope = this;
			
			scope.adjustFullScreen(richModalPanel);
	        jQuery(window).resize(function() {
	            scope.adjustFullScreen(richModalPanel);
	        });
		},
		
		adjustFullScreen : function(richModalPanel) {
	        var winObject = jQuery(window);
	
	        winH = winObject.height();
	        winW = winObject.width();
	        
	        jQuery('div[id=' + richModalPanel.contentDiv + ']').css ({
	            'width' : winW,
	            'height': winH,
	            'top'   : '0px',
	            'left'  : '0px'
	        });
	        
	        jQuery('table[id=' + richModalPanel.contentTable + ']').css ({
	        	'width' : winW
	        });
		}
	};
	
	Tacho.TogglePanel = {
		init : function(exClass, clClass, contentClass, opened) {
			var scope = this;
			jQuery(exClass).click(function() {
				scope.expand(exClass, clClass, contentClass);
	        });
	        jQuery(clClass).click(function() {
	        	scope.collapse(exClass, clClass, contentClass);
	        });
	        this.toggle(exClass, clClass, contentClass, opened);
		},
		toggle : function(exClass, clClass, contentClass, opened) {
			if (opened) {
				this.expand(exClass, clClass, contentClass);
			} else {
				this.collapse(exClass, clClass, contentClass);
			}
		},
		expand : function(exClass, clClass, contentClass) {
			jQuery(exClass).hide();
            jQuery(clClass).show();
            jQuery(contentClass).show();
		},
		collapse : function(exClass, clClass, contentClass) {
			jQuery(clClass).hide();
            jQuery(exClass).show();
            jQuery(contentClass).hide();
		}
	};
	
	Tacho.EnterpriseProcessTree = {
		selectedReferenceNr : null
	}

   	/** 
   	 *  creates plugin used for richfaces rich editor. This code is used for tinyMCE 3.x
   	 *  NOTE: we MUST include minus when we use this plugin, for example: "-tachoPlugin" or "save, -tachoPlugin"
   	 */  
    Tacho.Tinymce = {
		
		/**
		 * editor: the richfaces rich editor.
		 * cboId: the id of the control in plugin. It is used as the class name (with prefix 'mce_') which Richfaces generates for applying CSS. 
		 * selectItems: an array objects. These objects must have two properties: label and value
		 * titleList: the title for the list of selectItem. 
		 * onSelectHandler: callback function to process when an item is selected.
		 */
   		createComboBoxOnRichEditor : function(editor, cboId, selectItems, titleList, onSelectHandler) {
			// create control
			tinymce.create('tacho.tinymce.plugin.combobox', {
				// we only care createControl() method, others are unnecessary in this scenario. 
				createControl: function(controlName, controlManager) {
					switch (controlName) {
						case 'tachoComboBoxPlugin': // this is the short name of the combo-box, used to specified on the toolbar. 
						var listbox = controlManager.createListBox(cboId, {
																	title: titleList,
																	onselect : function(v) {
																		// get the scope to make sure we set content to the correct editor
																		onSelectHandler(this.scope.controlManager.editor,v);
																		
																	}
															  });
						// Add some values to the list box
						for(i = 0; i < selectItems.length; i++) {
							listbox.add(selectItems[i].label, selectItems[i].value);
						}

						// Return the new listbox instance
						return listbox;
					}
					
					return null;
					}});
       		
			// Register plugin with a short name
			tinymce.PluginManager.add('tachoPlugin', tacho.tinymce.plugin.combobox);
		}
	};

	Tacho.Utils = {
		/**
		 * Refresh current page with new conversation.
		 */
		refreshPage : function() {
			location.replace(jQuery.query.remove('cid').set('rdm', Math.random()).toString());
		},
		cut : function(str, max) {
			if (str.length > max) {
	        	return str.substring(0, max - 3) + '...';
	        }
			return str;
		}
	};
	
	Tacho.ProcessCmd = {
			setAcceptZone : function(acceptZoneId, transferZoneId) {
				jQuery("table[id=" + acceptZoneId + "] input[type=radio]").attr('checked', true);
				jQuery("table[id=" + transferZoneId + "] input[type=radio]").attr('checked', false);
				jQuery("table[id=" + transferZoneId + "] select").attr('disabled', true);
				jQuery("table[id=" + transferZoneId + "] textarea").attr('disabled', true);
			},
			
			setTransferZone : function(acceptZoneId, transferZoneId) {
				jQuery("table[id=" + acceptZoneId + "] input[type=radio]").attr('checked', false);
				jQuery("table[id=" + transferZoneId + "] input[type=radio]").attr('checked', true);
				jQuery("table[id=" + transferZoneId + "] select").attr('disabled', false);
				jQuery("table[id=" + transferZoneId + "] textarea").attr('disabled', false);
			}
	};
	
	Tacho.TextModuleTree = {
		nodeStateMap : {},
		expandAll : function(treeClientId) {
			var tree = document.getElementById(treeClientId).component;
			this.expand(tree);
		},
		expand : function(node) {
			if (node.isCollapsed && node.eventCollapsionClick && node.isCollapsed()) {
				node.eventCollapsionClick();
			}
			for ( var i = 0; i < node.childs.length; i++) {
				this.expand(node.childs[i]);
			}
		},
		expandFirstLevelNode : function(nodeClientId) {
			var node = document.getElementById(nodeClientId).component;
			if (node.isCollapsed && node.eventCollapsionClick && node.isCollapsed()) {
				node.eventCollapsionClick();
			}
		},
		collapseAll : function(treeClientId) {
			var tree = document.getElementById(treeClientId).component;
			this.collapse(tree);
		},
		collapse : function(node) {
			if (node.isCollapsed && node.eventCollapsionClick && !node.isCollapsed()) {
				node.eventCollapsionClick();
			}
			for ( var i = 0; i < node.childs.length; i++) {
				this.collapse(node.childs[i]);
			}
		},
		onNodeCollapsed : function(_event) {
			this.nodeStateMap[_event.collapsedNode] = false;
		},
		onNodeExpanded : function(_event) {
			this.nodeStateMap[_event.expandedNode] = true;
		},
		onTreeLoad : function(treeClientId) {
			for (var holdedNode in this.nodeStateMap) {
				if(holdedNode && holdedNode.indexOf(treeClientId) == 0) {
					if(this.nodeStateMap[holdedNode]) {
						document.getElementById(holdedNode).component.expand();
					} else{
						document.getElementById(holdedNode).component.collapse();
					}	
				}
			}
		}
	};
	
	Tacho.LtDataTooglePanel = {
		getSelectManyCheckboxText : function(id) {
			var result, selectedItems, i;
	        selectedItems = jQuery('table[id=' + id + '] input[type=checkbox]:checked');
	        result = [];
	        for (i=0; i < selectedItems.length; i++) {
	        	//jQuery('input[id=' + selectedItems[i].id + '] '
	            result.push(jQuery.trim(jQuery(selectedItems[i]).next('label').text()));
	        }
	        return result.join(', ');
		},
		getTimeScheduleText : function(divId, standardSchedule, standardText, comboId) {
			var selectedRadioValue = jQuery('div[id=' + divId + '] input[type=radio]:checked').attr('value');
			if (standardSchedule == selectedRadioValue) {
				// standard one is selected
				return standardText;
			}
			// else: combo is selected.
			return this.getComboText(comboId);
		},
		getComboText : function(comboId) {
			return jQuery('select[id=' + comboId + '] option:selected').text();
		},
		getSelectOneRadioText : function(id) {
			return jQuery.trim(jQuery('table[id=' + id + '] input[type=radio]:checked').next('label').text());
		},
		getProcessDateText : function(fromText, toText, divId) {
            var from = jQuery('div[id=' + divId + '] input[type=text].start-date').val();
            var to = jQuery('div[id=' + divId + '] input[type=text].end-date').val();
            return fromText + ' ' + from + ' ' + toText + ' ' + to;
		}
	};
	
	Tacho.LtData = {
	    onPeriodChange : function(divId, selectOneRadioId, altStyle, standardSchedule) {
	        var selectedRadio = jQuery('table[id=' + selectOneRadioId + '] input[type=radio]:checked').attr('value');
	        jQuery('div[id=' + divId + '] .' + altStyle).attr('disabled', standardSchedule == selectedRadio);
		}
	};
}